package com.telit.uav.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.telit.common.core.utils.FeignUtils;
import com.telit.common.core.utils.Result;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.BaiduUtils;
import com.telit.common.util.GeoUtils;
import com.telit.common.util.JwtTokenUtils;
import com.telit.common.util.TimeUtils;
import com.telit.firecommand.dto.DistrictCountDTO;
import com.telit.uav.dao.*;
import com.telit.uav.dto.CommUavDTO;
import com.telit.uav.dto.UavQueryDTO;
import com.telit.uav.dto.UavTaskDTO;
import com.telit.uav.entity.CommUav;
import com.telit.uav.service.UavQueryService;
import com.telit.uav.vo.*;
import com.telit.upms.feign.RemoteUpmsService;
import com.telit.upms.vo.MicroSysDistrictVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author zhouyu
 * @description 无人机查询实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UavQueryServiceImpl implements UavQueryService {

    @Autowired
    private CommUavDao commUavDao;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private AppCruiseTrackDao appCruiseTrackDao;

    @Autowired
    AppUavTrackDetailDao appUavTrackDetailDao;


    @Value("${uav.initialLongitude:118.533694}")
    private String initialLongitude;

    @Value("${uav.initialLatitude:32.082513}")
    private String initialLatitude;

    @Autowired
    private CommUavProducterDao commUavProducterDao;

    @Autowired
    private GeoXzqhCunDao geoXzqhCunDao;

    @Autowired
    private RemoteUpmsService remoteUpmsService;

    @Override
    public CommUav queryById(Long id) {
        CommUav commUav = commUavDao.selectByPrimaryKey(id);
        //TODO 后期此部分需要修改，先暂时进行处理
        if (StrUtil.equals(commUav.getEquipmentManufacturer(), "10017")) {
            commUav.setEquipmentManufacturer("大疆");
        }
        if (StrUtil.equals(commUav.getEquipmentModel(), "10018")) {
            commUav.setEquipmentModel("经纬M300RTK");
        }
        String districtCode = commUav.getDistrictCode();
        commUav.setDistrictName(commUavDao.queryDistrictNameByCode(districtCode));
        return commUav;
    }

    @Override
    public List<UavTaskDTO> queryByCondition(String uavCode, Integer isOnline, Integer isFlying) {

        List<CommUav> commUavs = null;
        if (isOnline != null) {
//            if (isOnline == 1) {
            commUavs = commUavDao.queryOnlineUav(uavCode, isFlying, 1);
//            } else if (isOnline == 0) {
//                commUavs = commUavDao.queryUnOnlineUav(uavCode);
//            }
        } else {
            //commUavs = commUavDao.queryAllUav(uavCode, isFlying);
        }

        if (commUavs == null || commUavs.size() == 0) {
            return null;
        }
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------start
        List<UavTaskDTO> taskPojos = new ArrayList<>(commUavs.size());
        for (CommUav commUav : commUavs) {
            UavTaskDTO uavTaskDTO = new UavTaskDTO();
            String code = commUav.getUavCode();
            String isConnect = commUavDao.queryIsConnect(code);
            uavTaskDTO.setUavCode(code);
            uavTaskDTO.setUavName(commUav.getUavName());
            uavTaskDTO.setEquipmentModel(commUav.getEquipmentModel());
            uavTaskDTO.setIsOnline(isConnect);
            String name = commUavDao.queryNameByCode(code);
            Map<String, String> map = appUavTrackDetailDao.selectLatelyLonAndLat(name);
            if (map != null && !map.isEmpty()) {
                uavTaskDTO.setLongitude(map.get("longitude"));
                uavTaskDTO.setLatitude(map.get("latitude"));
            } else {
                // 可能第一次无人机没有飞行记录,初始化一个经纬度
                uavTaskDTO.setLongitude(initialLongitude);
                uavTaskDTO.setLatitude(initialLatitude);
            }
            String resultStr = BaiduUtils.queryAddressByLaAndLo(uavTaskDTO.getLongitude(), uavTaskDTO.getLatitude());
            JSONObject result = JSON.parseObject(resultStr, JSONObject.class);
            uavTaskDTO.setLastPosition(result.getJSONObject("result").getString("formatted_address"));
            uavTaskDTO.setDistrictName(commUav.getDistrictName());
            uavTaskDTO.setMountDeviceType(commUav.getMountDeviceType());
            uavTaskDTO.setLiveShowUrl(commUav.getLiveShowUrl());
            uavTaskDTO.setToken(commUav.getToken());
            uavTaskDTO.setIsFlying(commUav.getIsFlying());
            Long status = commUavDao.queryStatus(code);
            if (status > 0) {
                //执行任务数量大于0
                uavTaskDTO.setIsPatrol("执行中");
                //获取
            } else {
                uavTaskDTO.setIsPatrol("0");
            }
            Long uavControllerId = commUavDao.queryUavController(code);
            //临时存储id
            uavTaskDTO.setUavUserName(Convert.toStr(uavControllerId));
            taskPojos.add(uavTaskDTO);
        }
        if (CollUtil.isNotEmpty(taskPojos)) {
            final List<Long> ids = taskPojos.stream()
                    .map(dto -> Convert.toLong(dto.getUavUserName()))
                    .collect(Collectors.toList());
            final Map<Long, String> idNameMapping = userInfoService.findAndConvertUserInfoByIds(ids);
            taskPojos.forEach(d -> {
                if (!StringUtils.isEmpty(d.getUavUserName())) {
                    d.setUavUserName(ObjectUtil.defaultIfNull(idNameMapping.get(Long.valueOf(d.getUavUserName())),
                            StrUtil.EMPTY));
                }
            });
        }
        return taskPojos;
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------end
    }


    @Override
    public UavSumVO queryByIsOnlineSum(String uavCode, Integer isOnline, String cityCode, Integer isFlying) {
        UavSumVO uavSumVO = new UavSumVO();
        //查询所有的行政区划代码，以及下无人机数量
        Integer cityCodelength = 2;
        if (StringUtils.isEmpty(cityCode)) {
            cityCodelength = 2;
            cityCode = "51";
        } else {
            cityCodelength = cityCode.length();
        }
        List<UavIsOnlineSumVO> list = commUavDao.queryByIsOnlineSum(cityCodelength, uavCode, isOnline, cityCode,
                isFlying);
        //补全name
        list.forEach(e -> e.setDistrictName(commUavDao.fingAllShiName(e.getLevelCode())));
        int onUnline = 0;
        int online = 0;
        //查询所有无人机

        List<UavVO> commUavs = commUavDao.queryAllUav(null, null, cityCode, cityCodelength);
        if (!CollectionUtils.isEmpty(commUavs)) {
            onUnline = commUavs.stream().filter(commUav -> commUav.getIsOnline() != 1).collect(
                    Collectors.toList()).size();
            online = commUavs.stream().filter(commUav -> commUav.getIsOnline() != 0).collect(
                    Collectors.toList()).size();
        }
        uavSumVO.setIsUnOnline(onUnline);
        uavSumVO.setAll(commUavs.size());
        uavSumVO.setIsOnline(online);
        uavSumVO.setList(list);
        uavSumVO.setAlllist(commUavs);

        //
        return uavSumVO;
    }

    //根据城市code查询下面对应区的无人机设备
    @Override
    public List<UavIsOnlineSumVO> queryUavByCityCode(String uavCode, Integer isOnline, String cityCode,
                                                     Integer isFlying) {
        String districtCode = JwtTokenUtils.getDistrictCode();
        List<UavIsOnlineSumVO> list = new ArrayList<>();
        if (!StringUtils.isEmpty(districtCode) && districtCode.length() == 6) {
            list = commUavDao.queryUavByCityCode(uavCode, isOnline, cityCode, isFlying, districtCode);
        } else {
            list = commUavDao.queryUavByCityCode(uavCode, isOnline, cityCode, isFlying, null);
        }

        for (UavIsOnlineSumVO uavIsOnlineSumVO : list) {
            uavIsOnlineSumVO.setDistrictName(commUavDao.fingXianName(uavIsOnlineSumVO.getLevelCode()));
            //将县下面所有的无人机返回
            List<UavVO> allUav = commUavDao.findAllUav(uavIsOnlineSumVO.getLevelCode());
            uavIsOnlineSumVO.setUavList(allUav);
        }
        return list;
    }


    //根据无人机id查询无人机信息
    @Override
    public UavVO queryUavById(Long id) {
        return commUavDao.queryUavById(id);

    }


    @Override
    public String queryNameById(Long id) {
        return commUavDao.queryNameById(id);
    }


    @Override
    public Long querySubTaskNumber(Long taskId, String status) {
        return appCruiseTrackDao.querySubTaskNumber(taskId, status);
    }

    @Override
    public Long queryDelayNumber(Long taskId, Date endTime) {
        String time = null;
        if (endTime != null) {
            time = TimeUtils.convertStringTime(endTime);
        }
        return appCruiseTrackDao.queryDelayNumber(taskId, time);
    }

    @Override
    public String queryCruisePointCollection(Long taskId, Long userId) {
        return appCruiseTrackDao.queryCruisePointCollection(taskId, userId);
    }

    /**
     * 查询所有在线无人机信息，返回List<Map<String,Object>>
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> selectListMap() {
        return commUavDao.selectListMap();
    }

    /**
     * 无人机巡航首页离线无人机信息
     *
     * @param uavCode
     * @return
     */
    @Override
    public UavTaskDTO getUnOnlineUavInfo(String uavCode) {
        List<UavTaskDTO> list = queryByCondition(uavCode, 0, null);
        UavTaskDTO uavTaskDTO = new UavTaskDTO();
        if (list != null && list.size() > 0) {
            uavTaskDTO = list.get(0);
            String name = commUavDao.queryNameByCode(uavTaskDTO.getUavCode());
            Map<String, String> map = appUavTrackDetailDao.selectLatelyLonAndLat(name);
            if (!map.isEmpty()) {
                uavTaskDTO.setLongitude(map.get("longitude"));
                uavTaskDTO.setLatitude(map.get("latitude"));
            }

        }
        return uavTaskDTO;
    }

    @Override
    public String queryNameByCode(String uavCode) {
        return commUavDao.queryNameByCode(uavCode);
    }

    @Override
    public Integer uavCount(Integer isFlying) {
        return commUavDao.uavTotal(isFlying);
    }

    @Override
    public List<CommUavDTO> queryByName(String uavName) {
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------start
        /*List<CommUav> commUavs = commUavDao.queryByName(uavName);
        List<CommUavDTO> commUavDTOList = new ArrayList<>();
        if (commUavs != null && commUavs.size() > 0) {
            commUavs.forEach(e -> {
                String uavCode = e.getUavCode();
                Long uav_user_id = commUavDao.queryFlyControllerByCode(uavCode);
                SysUserDetailVo userInfo = userInfoService.getUserInfo(uav_user_id);
                if (userInfo != null) {
                    e.setFlyController(userInfo.getRealName());
                }
                CommUavDTO commUavDTO = new CommUavDTO();
                BeanUtil.copyProperties(e, commUavDTO);
                commUavDTO.setEquipmentModelId(e.getEquipmentModel());
*//*            String equipmentModelId = e.getEquipmentModel();
            String equipmentModel = commUavDao.queryNameByEquipmentModelId(Long.parseLong(equipmentModelId));*//*
                commUavDTO.setEquipmentModel(StrUtil.isEmpty(e.getEquipmentModel()) ? null : commUavDao.queryNameByEquipmentModelId(Convert.toLong(e.getEquipmentModel())));
                commUavDTO.setProducterId(e.getEquipmentManufacturer());

           *//* String equipmentManufacturerId = e.getEquipmentManufacturer();
            String equipmentManufacturer = commUavDao.queryNameByEquipmentManufacturerId(Long.parseLong(equipmentManufacturerId));*//*
                commUavDTO.setEquipmentManufacturer(StrUtil.isEmpty(e.getEquipmentManufacturer()) ? null : commUavDao.queryNameByEquipmentManufacturerId(Convert.toLong(e.getEquipmentManufacturer())));
                commUavDTOList.add(commUavDTO);
            });
        }
        return commUavDTOList;*/
        List<CommUav> commUavs = commUavDao.queryByName(uavName);
        List<CommUavDTO> commUavDTOList = new ArrayList<>();
        if (commUavs != null && commUavs.size() > 0) {
            commUavs.forEach(e -> {
                String uavCode = e.getUavCode();
                final Long uav_user_id = commUavDao.queryFlyControllerByCode(uavCode);
                //临时存储
                e.setFlyController(Convert.toStr(uav_user_id));
                CommUavDTO commUavDTO = new CommUavDTO();
                BeanUtil.copyProperties(e, commUavDTO);
                commUavDTO.setEquipmentModelId(e.getEquipmentModel());
                commUavDTO.setEquipmentModel(StrUtil.isEmpty(e.getEquipmentModel()) ? null : commUavDao.queryNameByEquipmentModelId(Convert.toLong(e.getEquipmentModel())));
                commUavDTO.setProducterId(e.getEquipmentManufacturer());
                commUavDTO.setEquipmentManufacturer(StrUtil.isEmpty(e.getEquipmentManufacturer()) ? null : commUavDao.queryNameByEquipmentManufacturerId(Convert.toLong(e.getEquipmentManufacturer())));
                commUavDTOList.add(commUavDTO);
            });
        }
        if (CollUtil.isNotEmpty(commUavDTOList)) {
            final List<Long> ids = commUavDTOList.stream().map(d -> Convert.toLong(d.getFlyController())).collect(Collectors.toList());
            final Map<Long, String> idNameMapping = userInfoService.findAndConvertUserInfoByIds(ids);
            commUavDTOList.forEach(dto -> dto.setFlyController(
                    ObjectUtil.defaultIfNull(idNameMapping.get(dto.getFlyController()), StrUtil.EMPTY)
            ));
        }
        return commUavDTOList;
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------end
    }

    /**
     * 查询所有无人机设备厂商
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> listUavProducter() {
        return commUavDao.selectUavProducter();
    }

    /**
     * 根据设备厂家Id查询无人机型号
     *
     * @param producterId
     * @return
     */
    @Override
    public List<Map<String, Object>> getUavModelByProId(Long producterId) {
        return commUavDao.selectUavModelByProId(producterId);
    }

    /**
     * 根据uavCode查询token值
     *
     * @param uavCode
     * @return
     */
    @Override
    public String queryTokenByUavCode(String uavCode) {
        String token = commUavDao.selectTokenByUavCode(uavCode);
        return token;
    }

    @Override
    public List<CommUav> queryPositionCamera() {
        return commUavDao.queryPositionCamera();
    }


    @Override
    public List<UavVO> querySimpleDataByCondition(String radius, String longitude, String latitude, String flag) {
        String districtCode = "";
        if (StrUtil.isEmpty(flag)) {
            districtCode = JwtTokenUtils.getDistrictCode();
        }
        List<UavVO> result = new ArrayList<>();
        UavSumVO uavSumVO = queryByIsOnlineSum(null, null, districtCode, null);
        List<UavVO> alllist = uavSumVO.getAlllist();
        alllist.forEach(uavVO -> {
            double distance = GeoUtils.GetDistanceTwo(Double.parseDouble(longitude), Double.parseDouble(latitude),
                    new Double(uavVO.getLongitude()), new Double(uavVO.getLatitude()));
            if (distance <= Double.parseDouble(radius)) {
                result.add(uavVO);
            }
        });
        return result;
    }


    @Override
    public IPage<UavVO> listUavByPage(Integer current, Integer size, UavQueryDTO uavQueryDTO) {


//        if (org.apache.commons.lang3.StringUtils.isNotBlank(uavQueryDTO.getDistrictCode())){
//            uavQueryDTO.setDistrictCode(uavQueryDTO.getDistrictCode()+"%");
//        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(uavQueryDTO.getUavName())) {
            uavQueryDTO.setUavName("%" + uavQueryDTO.getUavName() + "%");
        }
        IPage<UavVO> uavIPage = new Page<>(current, size);
        IPage<UavVO> result = commUavDao.listUavByPage(uavIPage, uavQueryDTO);
        List<UavVO> records = result.getRecords();
        for (UavVO uavVO : records) {
            // 行政区划名称
            if (uavVO.getDistrictCode() != null) {
                uavVO.setDistrictName(
                        commUavDao.getNameByDistrictCode(uavVO.getDistrictCode(), uavVO.getDistrictCode().length()));
            }
        }
        uavIPage.setRecords(records);
        return result;
    }

    @Override
    public IPage<UavDeviceProducterVO> listDeviceProducterByPage(Integer current, Integer size, String name) {
        IPage<UavDeviceProducterVO> ipage = new Page<>(current, size);

        if (org.apache.commons.lang3.StringUtils.isNotBlank(name)) {
            name = "%" + name + "%";
        }
        IPage<UavDeviceProducterVO> result = commUavDao.listDeviceProducterByPage(ipage, name);
        return result;
    }

    @Override
    public List<CommUavModelVO> listDeviceModel(String name) {

        if (org.apache.commons.lang3.StringUtils.isNotBlank(name)) {
            name = "%" + name + "%";
        }
        List<CommUavModelVO> result = commUavDao.listDeviceModelByPage(name);
        return result;
    }


    @Override
    public void deleteDeviceProducter(Long id) {
        //判断改设备厂商下面是否含有型号
        Integer producter = commUavDao.findProducter(id);
        if (producter != null && producter > 0) {
            throw new ForestBaseException("该设备厂商下面存在无人机型号");
        }
        commUavProducterDao.deleteById(id);
    }

    /**
     * 查询无人机token,去除uav表中已有token
     *
     * @return
     */
    @Override
    public List<String> listUavToken() {
        List<String> uavTokenList = commUavDao.selectUavToken();
        if (uavTokenList != null) {
            Iterator<String> iterator = uavTokenList.iterator();
            while (iterator.hasNext()) {
                String uavToken = iterator.next();
                int count = commUavDao.selectUavCountBytoken(uavToken);
                if (count > 0) {
                    iterator.remove();
                }
            }
        }
        return uavTokenList;
    }

    @Override
    public DistrictCountDTO qryNumByParentCode(Integer isOnline, String uavName, String districtCode) {
        List<CommUav> all = commUavDao.queryAllUav2(uavName, null, districtCode);
        List<CommUav> online = commUavDao.queryOnlineUav2(uavName, 1, districtCode);
        Integer offlineCount = all.size() - online.size();
        return DistrictCountDTO.builder()
                .count(all.size())
                .offlineCount(offlineCount)
                .onlineCount(online.size())
                .build();
    }

    @Override
    public DistrictCountDTO qryDistrictListByParentCode(Integer isOnline, String uavName, String districtCode) {
        //根据行政区划编码查询行政区划ID
        com.telit.common.core.utils.Result<Map<String, MicroSysDistrictVo>> selectDistrictDetailByListCodesResult = remoteUpmsService.selectDistrictDetailByListCodes(
                Collections.singletonList(districtCode));
        Map<String, MicroSysDistrictVo> microSysDistrictVoMap = FeignUtils.unwrap(
                selectDistrictDetailByListCodesResult);
        MicroSysDistrictVo microSysDistrictVo = microSysDistrictVoMap.get(districtCode);

        //无人机列表
        List<CommUav> countList = commUavDao.queryListLike(uavName, null, isOnline, districtCode);
        List<UavTaskDTO> uavTaskDTOS = buildUav(districtCode, uavName, isOnline);

        //子行政区划
        Result<List<MicroSysDistrictVo>> selectDistrictDetailForUnderRankByCode = remoteUpmsService.selectDistrictDetailForUnderRankByCode(
                districtCode);
        List<MicroSysDistrictVo> microSysDistrictVos = FeignUtils.unwrap(selectDistrictDetailForUnderRankByCode);
        List<DistrictCountDTO> child = new ArrayList<>();
        microSysDistrictVos.forEach(districtVo -> {
            List<CommUav> childCountList = commUavDao.queryListLike(uavName, null, isOnline,
                    districtVo.getCode());
            List<UavTaskDTO> childUavTaskDTOS = buildUav(districtVo.getCode(), uavName, isOnline);
            child.add(DistrictCountDTO.builder()
                    .name(districtVo.getName())
                    .code(districtVo.getCode())
                    .count(childCountList.size())
                    .uavList(childUavTaskDTOS)
                    .build());
        });

        //构建返回DTO
        return DistrictCountDTO.builder()
                .name(microSysDistrictVo.getName())
                .code(microSysDistrictVo.getCode())
                .count(countList.size())
                .uavList(uavTaskDTOS)
                .children(child)
                .build();
    }

    /**
     * 查询无人机树形结构
     *
     * @param districtCode 行政区划编码
     * @param uavName      无人机名称
     *
     * @return UavTreeDTO
     */
    public List<UavTaskDTO> buildUav(String districtCode, String uavName, Integer isOnline) {
        List<CommUav> uavList = commUavDao.queryList(uavName, null, isOnline, districtCode);
        //无人机属性赋值
        List<UavTaskDTO> taskPojos = new ArrayList<>(uavList.size());
        List<String> uavCodeList = CollectionUtil.newArrayList();
        List<String> uavNameList = CollectionUtil.newArrayList();
        for (CommUav commUav : uavList) {
            UavTaskDTO uavTaskDTO = new UavTaskDTO();
            String code = commUav.getUavCode();
            //设置uavCode
            uavCodeList.add(code);
            //设置无人机名称
            uavNameList.add(commUav.getUavName());
            //复制实体的值
            BeanUtil.copyProperties(commUav, uavTaskDTO);
            uavTaskDTO.setUavCode(code);
            taskPojos.add(uavTaskDTO);
        }

        //根据无人机编码集合查询无人机的连接状态和飞手ID
        List<Map<String, Object>> connectAndUserIdList = commUavDao.queryConnectAndUserIdByCodeList(
                uavCodeList);
        //存放无人机code对应的连接信息
        Map<String, String> connectMap = CollectionUtil.newHashMap();
        //存放飞手ID集合
        List<Long> uavUserIdList = CollectionUtil.newArrayList();
        //存放无人机code对应的飞手ID
        Map<String, Long> uavUserIdMap = CollectionUtil.newHashMap();
        if (CollectionUtil.isNotEmpty(connectAndUserIdList)) {
            connectMap = connectAndUserIdList.stream().collect(
                    Collectors.toMap(e -> Convert.toStr(e.get("uav_code")),
                            e -> Convert.toStr(e.get("is_connect"))));
            uavUserIdList = connectAndUserIdList.stream().map(
                    e -> Convert.toLong(e.get("uav_user_id"))).collect(Collectors.toList());
            uavUserIdMap = connectAndUserIdList.stream().collect(
                    Collectors.toMap(e -> Convert.toStr(e.get("uav_code")),
                            e -> Convert.toLong(e.get("uav_user_id"))));
        }

        //根据无人机名称查询经纬度信息
        List<Map<String, String>> lonAndLatByUavNameList = appUavTrackDetailDao.selectLateLonAndLatByUavNameList(
                uavNameList);
        //把集合转换成map
        Map<String, Map<String, String>> uavNameMap = CollectionUtil.newHashMap();
        if (CollectionUtil.isNotEmpty(lonAndLatByUavNameList)) {
            uavNameMap = lonAndLatByUavNameList.stream().collect(
                    Collectors.toMap(e -> e.get("uav_name"), e -> e, (e1, e2) -> e1));
        }

        //根据无人机的code查询是否在执行任务中
        List<Map<String, Object>> statusList = commUavDao.queryStatusByCodeList(uavCodeList);
        //把集合转换成状态map
        Map<String, String> statusMap = CollectionUtil.newHashMap();
        if (CollectionUtil.isNotEmpty(statusList)) {
            statusMap = statusList.stream().collect(
                    Collectors.toMap(e -> MapUtil.getStr(e, "uav_code"), e -> MapUtil.getStr(e, "count")));
        }

        if (CollUtil.isNotEmpty(taskPojos)) {
            final Map<Long, String> idNameMapping = userInfoService.findAndConvertUserInfoByIds(
                    uavUserIdList);
            Map<String, String> finalConnecteMap = connectMap;
            Map<String, Long> finalUavUserIdMap = uavUserIdMap;
            Map<String, Map<String, String>> finalUavNameMap = uavNameMap;
            Map<String, String> finalStatusMap = statusMap;
            taskPojos.forEach(d -> {
                //设置无人机名称
                if (ObjectUtil.isNotEmpty(finalUavUserIdMap.get(d.getUavCode()))) {
                    d.setUavUserName(ObjectUtil.defaultIfNull(
                            idNameMapping.get(finalUavUserIdMap.get(d.getUavCode())), StrUtil.EMPTY));
                }
                //设置无人机在离线状态
                if (finalConnecteMap != null && !finalConnecteMap.isEmpty()) {
                    d.setIsOnline(ObjectUtil.defaultIfNull(finalConnecteMap.get(d.getUavCode()),
                            StrUtil.EMPTY));
                }
                //设置无人机经纬度信息
                if (finalUavNameMap != null && !finalUavNameMap.isEmpty() && ObjectUtil.isNotEmpty(
                        finalUavNameMap.get(d.getUavName()))) {
                    d.setLongitude(ObjectUtil.defaultIfNull(
                            (finalUavNameMap.get(d.getUavName())).get("longitude"), StrUtil.EMPTY));
                    d.setLatitude(ObjectUtil.defaultIfNull(
                            (finalUavNameMap.get(d.getUavName())).get("latitude"), StrUtil.EMPTY));
                } else {
                    // 可能第一次无人机没有飞行记录,初始化一个经纬度
                    d.setLongitude(initialLongitude);
                    d.setLatitude(initialLatitude);
                }
                String resultStr = BaiduUtils.queryAddressByLaAndLo(d.getLongitude(), d.getLatitude());
                if (StrUtil.isNotEmpty(resultStr)) {
                    JSONObject result1 = JSON.parseObject(resultStr, JSONObject.class);
                    if (ObjectUtil.isNotEmpty(result1.getJSONObject("result")) && StrUtil.isNotEmpty(
                            result1.getJSONObject("result").getString("formatted_address"))) {
                        d.setLastPosition(
                                result1.getJSONObject("result").getString("formatted_address"));
                    }
                }

                //设置是否在执行任务
                if (StrUtil.isNotEmpty(finalStatusMap.get(d.getUavCode()))) {
                    Integer count = Convert.toInt(finalStatusMap.get(d.getUavCode()));
                    if (count > 0) {
                        //执行任务数量大于0
                        d.setIsPatrol("执行中");
                        //获取
                    } else {
                        d.setIsPatrol("0");
                    }
                }
            });
        }

        return taskPojos;
    }

}
